package com.runen.wnhz.runen.ui.adapter.puadapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.ruffian.library.RTextView;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.CancleOrderBean;
import com.runen.wnhz.runen.bean.MyOrderBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.activity.major.IntroductionActivity;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MyOrderListAdapter extends BaseAdapter {

    private Context context;

    private List<MyOrderBean.DataBean.ListBean> listBeans;

    private String token;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
             switch (msg.what){
                 case 0:
                     ToastUtil.showToast("数据请求失败");
                     break;
                 case 1:
                     String info = (String) msg.obj;
                     ToastUtil.showToast(info);
                     listBeans.remove(msg.arg1);
                     notifyDataSetChanged();
                     break;
                 case 2:
                     String info1 = (String) msg.obj;
                     ToastUtil.showToast(info1);
                     break;
                 case 3:
                     context.startActivity(new Intent(context, LoginForPersonalActivity.class));
                     break;
             }
        }
    };

    public MyOrderListAdapter(Context context, List<MyOrderBean.DataBean.ListBean> listBeans) {
        this.context = context;
        this.listBeans = listBeans;
    }

    @Override
    public int getCount() {
        if(listBeans != null){
            return listBeans.size();
        }else {
            return 0;
        }
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        String orderStatus;
        ViewHolder viewHolder;
        if(convertView == null){
            convertView = View.inflate(context, R.layout.item_mine_order,null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder)convertView.getTag();
        }
        final MyOrderBean.DataBean.ListBean listBean = listBeans.get(position);
        viewHolder.item_mine_order_time_tv.setText(listBean.getOrder_time());
        viewHolder.item_mine_order_no_tv.setText("订单：" + listBean.getOrder_no());
        String status = listBean.getOrder_status();
        if("0".equals(status)){
            orderStatus = "已取消";
            viewHolder.linear_my_order.setVisibility(View.GONE);
        }else if("1".equals(status)){
            orderStatus = "待支付";
            viewHolder.linear_my_order.setVisibility(View.VISIBLE);
        }else if("2".equals(status)){
            orderStatus = "待发货";
            viewHolder.linear_my_order.setVisibility(View.VISIBLE);
        }else if("3".equals(status)){
            orderStatus = "待收货";
            viewHolder.linear_my_order.setVisibility(View.VISIBLE);
        }else{
            orderStatus = "已完成";
            viewHolder.linear_my_order.setVisibility(View.VISIBLE);
        }
        viewHolder.item_mine_order_status_tv.setText(orderStatus);
        Glide.with(context).load(listBean.getGoods_pic()).into(viewHolder.item_mine_order_pic_iv);
        viewHolder.item_mine_order_title_tv.setText(listBean.getGoods_name());
        viewHolder.item_mine_order_aging_time_tv.setText("有效期：" + listBean.getAging_time());
        viewHolder.item_mine_order_score_tv.setRating(Float.parseFloat(listBean.getStar()));
        viewHolder.item_mine_order_price_tv.setText("¥" + listBean.getTotal_fee());
        if("0".equals(listBean.getHave_file())){
           viewHolder.item_mine_order_data_ll.setVisibility(View.GONE);
        }else if("1".equals(listBean.getHave_file())){
            viewHolder.item_mine_order_data_ll.setVisibility(View.VISIBLE);
        }else{
            viewHolder.item_mine_order_data_ll.setVisibility(View.VISIBLE);
        }
        viewHolder.item_mine_order_data_rv.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        MyOrderDataAdapter adapter = new MyOrderDataAdapter(context, listBean.getOtherList());
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MyOrderBean.DataBean.ListBean.OtherListBean otherListBean = listBean.getOtherList().get(position);
                Intent intent = new Intent(context, IntroductionActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("pic", otherListBean.getGoods_pic());
                bundle.putString("lid", otherListBean.getData_id());
                intent.putExtras(bundle);
                context.startActivity(intent);
            }
        });
        if(position == (listBeans.size() - 1)){
            viewHolder.view.setVisibility(View.GONE);
        }else{
            viewHolder.view.setVisibility(View.VISIBLE);
        }
        viewHolder.item_mine_order_data_rv.setAdapter(adapter);
        viewHolder.item_mine_order_cancel_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  cancleOrder(listBean.getOrder_id(),position);
            }
        });
        viewHolder.item_mine_order_pay_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        return convertView;
    }

    private void cancleOrder(String orderId, final int position){
        ACacheUtlis cacheUtlis = ACacheUtlis.getInstance();
        if(cacheUtlis != null){
            UserBean reqeustUser = cacheUtlis.getReqeustUser(context);
            if(reqeustUser != null){
                token = reqeustUser.getToken();
                FormBody formBody = new FormBody.Builder().add("token", ACacheUtlis.getInstance().getReqeustUser(context).getToken()).add("order_id",orderId).build();
                Request request = new Request.Builder().url(NetUtils.CANCLE_ORDER_INFO).post(formBody).build();
                Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
                newCall.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                       if(response.isSuccessful()){
                           ResponseBody responseBody = response.body();
                           if(responseBody != null){
                               String json = responseBody.string();
                               CancleOrderBean cancleOrderBean = new Gson().fromJson(json, CancleOrderBean.class);
                               if(cancleOrderBean != null){
                                   String re = cancleOrderBean.getRe();
                                   Message message = Message.obtain();
                                   if("1".equals(re)){
                                       message.what = 1;
                                       message.obj = cancleOrderBean.getInfo();
                                       message.arg1 = position;
                                       handler.sendMessage(message);
                                   }else if("0".equals(re)){
                                       message.what = 2;
                                       message.obj = cancleOrderBean.getInfo();
                                       handler.sendMessage(message);
                                   }else if("-1".equals(re)){
                                       message.what = 3;
                                       handler.sendMessage(message);
                                   }
                               }
                           }
                       }
                    }
                });
            }
        }
    }

    static class ViewHolder {
        @BindView(R.id.item_mine_order_time_tv)
        TextView item_mine_order_time_tv;
        @BindView(R.id.item_mine_order_no_tv)
        TextView item_mine_order_no_tv;
        @BindView(R.id.item_mine_order_status_tv)
        TextView item_mine_order_status_tv;
        @BindView(R.id.item_mine_order_pic_iv)
        ImageView item_mine_order_pic_iv;
        @BindView(R.id.item_mine_order_title_tv)
        TextView item_mine_order_title_tv;
        @BindView(R.id.item_mine_order_aging_time_tv)
        TextView item_mine_order_aging_time_tv;
        @BindView(R.id.item_mine_order_score_tv)
        RatingBar item_mine_order_score_tv;
        @BindView(R.id.item_mine_order_price_tv)
        TextView item_mine_order_price_tv;
        @BindView(R.id.item_mine_order_data_rv)
        RecyclerView item_mine_order_data_rv;
        @BindView(R.id.item_mine_order_cancel_tv)
        RTextView item_mine_order_cancel_tv;
        @BindView(R.id.item_mine_order_pay_tv)
        RTextView item_mine_order_pay_tv;
        @BindView(R.id.item_mine_order_data_ll)
        LinearLayout item_mine_order_data_ll;
        @BindView(R.id.view)
        View view;
        @BindView(R.id.linear_my_order)
        LinearLayout linear_my_order;

        public ViewHolder(View convertView) {
            ButterKnife.bind(this,convertView);
        }
    }
}
